package com.yc.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yc.config.OssConfig;
import com.yc.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    OssConfig ossConfig;

    @Async
    @Override
    public CompletableFuture<String> upload(MultipartFile file) {
        String bucketName = ossConfig.getBucketName();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String originalFilename = file.getOriginalFilename();
        String filename= UUID.randomUUID().toString().replaceAll("-", "")+originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName="uploads/"+filename;
        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            ossClient.shutdown();
        }
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
        return CompletableFuture.completedFuture(url);

    }

    @Override
    public List<String> upload(MultipartFile[] files) {
        ArrayList<String> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            CompletableFuture<String> fileUrlFuture = upload(file);
            try {
                urls.add(fileUrlFuture.get());
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
        return urls;
    }



}
